<?php
class Device_libModel extends Model {
	public function get_primary_key() {
		return $this->primary_key = 'id'; //设置主键
	}
	public function get_fields() {
		return $this->get_table_fields();
	}

	/**
	 * 为代理商分配设备号
	 * @param $data
	 * @return bool
	 */
	public function alletDevice($data)
	{
		try {
			$agentId = $data['agentId'];
			//更新device_lib表数据
			$sql = 'update ca_device_lib set pid='.$agentId.',update_time='.$data['update_time'].',status=1,layer=concat_ws("|",layer,'.$agentId.') where status=0 and pid='.$data['userid'].' order by id asc limit '.$data['num'];
			$this->db->query($sql);
			$isUpdate = $this->db->affected_rows();	//影响记录条数
			if(empty($isUpdate)){return false;}
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return true;
	}

	/**
	 * 获取设备库中未分配的设备数量
	 * @param $uid
	 * @return mixed
	 */
	function getDeviceLibCount($uid){
		try {
			$query = $this->db->query('SELECT count(id) as num FROM ca_device_lib WHERE pid='.$uid.' and status=0');
			$result = $query->row();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}


	/**
	 * 查询设备库中是否存在该设备
	 * @param $uid
	 * @return mixed
	 */
	function getDeviceByDeviceNum($DeviceNum){
		try {
			$query = $this->db->query("SELECT * FROM ca_device_lib WHERE 2g='$DeviceNum' limit 1");
			$result = $query->row();
		} catch (Exception $e) {
			log_message('error',  $e->getMessage());
		}
		return $result;
	}
}